<template>
  <div class="login-container starry-bg">
    <!-- 星星背景 -->
    <div class="stars"></div>
    <div class="stars2"></div>
    <div class="stars3"></div>

    <!-- 登录/注册卡片 -->
    <div class="login-card glass rounded-xl fade-in">
      <h1 class="title text-gradient">趣味英语</h1>
      <p class="subtitle">快乐学习，轻松背单词 🎮</p>

      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 登录表单 -->
        <el-tab-pane label="登录" name="login">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="login-form">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleLogin"
              class="submit-btn gradient-bg"
            >
              登录
            </el-button>
          </el-form>
        </el-tab-pane>

        <!-- 注册表单 -->
        <el-tab-pane label="注册" name="register">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="login-form">
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="school">
              <el-input
                v-model="registerForm.school"
                placeholder="请输入学校名称"
                size="large"
                prefix-icon="School"
              />
            </el-form-item>
            <el-form-item prop="grade">
              <el-select
                v-model="registerForm.grade"
                placeholder="请选择年级"
                size="large"
                style="width: 100%"
              >
                <el-option label="三年级上学期" value="三上" />
                <el-option label="三年级下学期" value="三下" />
                <el-option label="四年级上学期" value="四上" />
                <el-option label="四年级下学期" value="四下" />
                <el-option label="五年级上学期" value="五上" />
                <el-option label="五年级下学期" value="五下" />
                <el-option label="六年级上学期" value="六上" />
                <el-option label="六年级下学期" value="六下" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择头像（十二生肖）">
              <div class="avatar-selector">
                <div
                  v-for="(emoji, index) in avatarEmojis"
                  :key="index"
                  class="avatar-item"
                  :class="{ active: registerForm.avatar === `avatar${index + 1}` }"
                  @click="registerForm.avatar = `avatar${index + 1}`"
                  :title="avatarNames[index]"
                >
                  {{ emoji }}
                </div>
              </div>
            </el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleRegister"
              class="submit-btn gradient-bg-2"
            >
              注册
            </el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { LoginForm, RegisterForm, Grade } from '@/types'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('login')
const loading = ref(false)

// 十二生肖头像
const avatarEmojis = ['🐭', '🐮', '🐯', '🐰', '🐲', '🐍', '🐴', '🐏', '🐵', '🐔', '🐶', '🐷']
const avatarNames = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪']
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

const loginForm = reactive<LoginForm>({
  username: '',
  password: ''
})

const registerForm = reactive<RegisterForm>({
  username: '',
  password: '',
  school: '',
  grade: '' as Grade,
  avatar: 'avatar1'
})

const loginRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const registerRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度6-30个字符', trigger: 'blur' }
  ],
  school: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
  grade: [{ required: true, message: '请选择年级', trigger: 'change' }]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log('=== 开始登录 ===')
      console.log('表单数据:', loginForm)
      
      loading.value = true
      const success = await userStore.login(loginForm)
      loading.value = false
      
      console.log('登录结果:', success)
      
      if (success) {
        // 根据用户类型跳转不同页面
        const targetPath = userStore.user?.isAdmin ? '/admin' : '/dashboard'
        console.log('准备跳转到', targetPath)
        await router.push(targetPath)
        console.log('跳转完成')
      } else {
        console.log('登录失败，未跳转')
      }
    }
  })
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log('=== 开始注册 ===')
      console.log('表单数据:', registerForm)
      
      loading.value = true
      const success = await userStore.register(registerForm)
      loading.value = false
      
      console.log('注册结果:', success)
      
      if (success) {
        // 普通用户注册后跳转到Dashboard
        console.log('准备跳转到 /dashboard')
        await router.push('/dashboard')
        console.log('跳转完成')
      } else {
        console.log('注册失败，未跳转')
      }
    }
  })
}
</script>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

/* 星星动画 */
.stars,
.stars2,
.stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image: radial-gradient(2px 2px at 20px 30px, #eee, rgba(0, 0, 0, 0)),
    radial-gradient(2px 2px at 40px 70px, #fff, rgba(0, 0, 0, 0)),
    radial-gradient(1px 1px at 90px 40px, #fff, rgba(0, 0, 0, 0));
  background-repeat: repeat;
  background-size: 200px 200px;
  animation: zoom 20s infinite;
  opacity: 0;
}

.stars2 {
  background-image: radial-gradient(1px 1px at 30px 50px, #ddd, rgba(0, 0, 0, 0)),
    radial-gradient(2px 2px at 60px 80px, #fff, rgba(0, 0, 0, 0));
  background-repeat: repeat;
  background-size: 300px 300px;
  animation: zoom 30s infinite;
}

.stars3 {
  background-image: radial-gradient(1px 1px at 50px 60px, #fff, rgba(0, 0, 0, 0)),
    radial-gradient(1px 1px at 100px 120px, #ddd, rgba(0, 0, 0, 0));
  background-repeat: repeat;
  background-size: 400px 400px;
  animation: zoom 40s infinite;
}

@keyframes zoom {
  0% {
    opacity: 0;
    transform: scale(0.5);
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: scale(1.2);
  }
}

.login-card {
  width: 90%;
  max-width: 450px;
  padding: 40px;
  position: relative;
  z-index: 10;
}

.title {
  font-size: 2.5rem;
  font-weight: bold;
  text-align: center;
  margin-bottom: 10px;
}

.subtitle {
  text-align: center;
  color: #fff;
  margin-bottom: 30px;
  font-size: 1.1rem;
}

.login-tabs {
  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    color: rgba(255, 255, 255, 0.7);
    font-size: 1.1rem;
  }

  :deep(.el-tabs__item.is-active) {
    color: #fff;
  }

  :deep(.el-tabs__active-bar) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
}

.login-form {
  margin-top: 30px;

  .el-form-item {
    margin-bottom: 20px;
  }

  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    color: #fff;
  }

  :deep(.el-input__inner::placeholder) {
    color: rgba(255, 255, 255, 0.5);
  }

  :deep(.el-select__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: none;
  }
}

.avatar-selector {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.avatar-item {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: scale(1.1);
    border-color: rgba(255, 255, 255, 0.5);
  }

  &.active {
    border-color: #667eea;
    box-shadow: 0 0 10px rgba(102, 126, 234, 0.5);
  }
}

.submit-btn {
  width: 100%;
  font-size: 1.1rem;
  height: 45px;
  border: none;
  margin-top: 10px;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
  }
}
</style>

